﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;

namespace RefOffDesktop
{
    /*
     * Class: Goal
     * 
     * Use: Form allowing the user to edit the club and scorer
     *      for goals within a match
     *      
     * Author: Mike Skaife, mcs3@aber.ac.uk
     */ 
    public partial class Goal : Form
    {
        //The Match which the goal was scored in
        private Match mReferrer;


        //Details of the Goal taken from the database
        private int gGoal_id;
        private int gPlayer_id;
        private String gPlayerName;
        private int gMatchId;
        private String gTime;
        private int gOwnGoal;
        private String gClub;
        private int gClubId;
        private int gOtherClubId;
        private String gOtherClub;

        //Details required to connect to the database
        SqlCeConnection conn;
        String conString;
        String desktop_connection = @"Data Source=RefOff_DB.sdf";

        //Variable used when editing goal to determine
        //which teams players to display in a combo box
        private String goalClub = "this";

        //Array of all the players from both teams in the Match
        //where this Goal was scored
        public List<Player> goalMatchPlayers;

        //Arrays to hold separate home and away squads
        public List<Player> goalThisClubPlayers;
        public List<Player> goalOtherClubPlayers;
             
        //Constructor passed a Match object
        public Goal(Match sender)
        {
            InitializeComponent();
            referrer = sender;
            goalMatchPlayers = new List<Player>();
            goalThisClubPlayers = new List<Player>();
            goalOtherClubPlayers = new List<Player>();

            //Split the players up into home and away
            setupPlayerArrays();
        }

        //Constructor when no Match object is passed
        public Goal()
        {
            InitializeComponent();
            goalMatchPlayers = new List<Player>();
            goalThisClubPlayers = new List<Player>();
            goalOtherClubPlayers = new List<Player>();

            //Split the players up into home and away
            setupPlayerArrays();
        }

        //Method used to split all players from the match into
        //separate home and away arrays
        public void setupPlayerArrays()
        {
            //Loop through all the players from the Match
            for(int i = 0; i < goalMatchPlayers.Count; i++)
            {
                if (goalMatchPlayers[i].club_id == gClubId)
                {
                    //Players from goalscoring team
                    goalThisClubPlayers.Add(goalMatchPlayers[i]);
                }
                else
                {
                    //Players from other team
                    goalOtherClubPlayers.Add(goalMatchPlayers[i]);
                }
            }
        }

        //Initialise the selected value of the Club combo box
        public void initClub()
        {
            if (goalClub.Equals("this"))
            {                
                goalClubCombo.SelectedIndex = 0;
            }
            else
            {
                goalClubCombo.SelectedIndex = 1;
            }
        }

        //Initialise the selected value of the Player combo box
        public void initPlayer()
        {
            //Clear the combo box
            goalPlayerCombo.Items.Clear();
            if(goalClub.Equals("this"))
            {
                for(int i = 0; i < goalThisClubPlayers.Count; i++)
                {
                    //Add all players from goalscoring teame
                    goalPlayerCombo.Items.Add(goalThisClubPlayers[i].name);
                }
            }
            else
            {
                for (int i = 0; i < goalOtherClubPlayers.Count; i++)
                {
                    //Or add all players from the other team
                    goalPlayerCombo.Items.Add(goalOtherClubPlayers[i].name);
                }
            }
            
            //Vairables to store index values
            int index = 0;
            int counter = 0;

            //Go through each player in the combo box
            for (int i = 0; i < goalPlayerCombo.Items.Count; i++)
            {
                //If the player is the one who scored the goal
                if (goalPlayerCombo.Items[i].ToString().Equals(player_name))
                {
                    //Get hold of the current index
                    index = counter;
                }
                counter++;
            }

            //Set the player as the default selected item in the combo
            //box for when the form is next displayed
            goalPlayerCombo.SelectedIndex = index;
        }

        //Initialist the checkbox indicating whether or not
        //the Goal is an own goal
        public void initOwnGoal()
        {
            if (gOwnGoal == 1)
            {
                //Tick it if it is an own goal
                goalOwnGoalChk.Checked = true;
            }
            else
            {
                //Leave unticked if not an own goal
                goalOwnGoalChk.Checked = false;
            }
        }

        //Setter and getter for database id of Goal
        public int goal_id
        {
            get
            {
                return gGoal_id;
            }

            set
            {
                gGoal_id = value;
            }
        }

        //Setter and getter for database id of player who scored Goal
        public int player_id
        {
            get
            {
                return gPlayer_id;
            }

            set
            {
                gPlayer_id = value;
            }
        }

        //Setter and getter for full name of player who scored (number, firstname, surname)
        public String player_name
        {
            get
            {
                return gPlayerName;
            }

            set
            {
                gPlayerName = value;
            }
        }

        //Setter and getter for database id of match the Goal was scored in
        public int match_id
        {
            get
            {
                return gMatchId;
            }

            set
            {
                gMatchId = value;
            }
        }

        //Setter and getter for time the Goal was scored at
        public String time
        {
            get
            {
                return gTime;
            }

            set
            {
                gTime = value;
            }
        }

        //Setter and getter for own goal value where 1 = own goal, 0 = not own goal
        public int own_goal
        {
            get
            {
                return gOwnGoal;
            }

            set
            {
                gOwnGoal = value;
            }
        }

        //Setter and getter for database id of club that scored
        public int clubId
        {
            get
            {
                return gClubId;
            }

            set
            {
                gClubId = value;
            }
        }

        //Setter and getter for databse id of club goal was scored against
        public int otherClubId
        {
            get
            {
                return gOtherClubId;
            }

            set
            {
                gOtherClubId = value;
            }
        }

        //Setter and getter for name of club that scored
        public String club
        {
            get
            {
                return gClub;
            }

            set
            {
                gClub = value;
            }
        }

        //Setter and getter for name of club scored against
        public String otherClub
        {
            get
            {
                return gOtherClub;
            }

            set
            {
                gOtherClub = value;
            }
        }

        //Setter and getter for corresponding Match object
        public Match referrer
        {
            get
            {
                return mReferrer;
            }

            set
            {
                mReferrer = value;
            }
        }

        //This method is called when the 'Save' button is clicked
        private void goalSaveBtn_Click(object sender, EventArgs e)
        {
            //Get hold of index and value of selected Club
            int clubIndex = goalClubCombo.SelectedIndex;
            String selectedClub = goalClubCombo.Items[clubIndex].ToString();

            //Set variable to indicate which club scored
            if (selectedClub.Equals(club))
            {
                goalClub = "this";
            }
            else
            {
                goalClub = "other";
            }

            //Get hold of index and value of selected player
            int playerIndex = goalPlayerCombo.SelectedIndex;
            String selectedPlayer = goalPlayerCombo.Items[playerIndex].ToString();

            //Variable to hold id of Player who scored
            int newPlayerId = 0;

            //If the first club scored...
            if (goalClub.Equals("this"))
            {
                //Go through the team
                for(int i = 0; i < goalThisClubPlayers.Count; i++)
                {
                    if (goalThisClubPlayers[i].name.Equals(selectedPlayer))
                    {
                        //And get hold of database id of player who scored
                        newPlayerId = goalThisClubPlayers[i].player_id;
                    }
                }
            }
            //Otherwise for the other team...
            else
            {
                //Go through the squad
                for(int i = 0; i < goalOtherClubPlayers.Count; i++)
                {
                    if (goalOtherClubPlayers[i].name.Equals(selectedPlayer))
                    {
                        //And get the database id for the player who scored
                        newPlayerId = goalOtherClubPlayers[i].player_id;
                    }
                }
            }

            //Check if this has been labelled as an own goal
            if (goalOwnGoalChk.Checked == true)
            {
                //If it is an own goal set value of variable for use in database
                //query, and set text in Match Details screen to reflect this
                own_goal = 1;
                referrer.matchGoalLst.SelectedItems[0].SubItems[2].Text = "Yes";
            }
            else
            {
                //If it is not an own goal set value of variable for use in database
                //query and update Match Details screen
                own_goal = 0;
                referrer.matchGoalLst.SelectedItems[0].SubItems[2].Text = "No";
            }
               
            //Connect to the database
            connectToDatabase(desktop_connection);

            //Create and execute SQL command to update details of Goal in database
            string goal_update_command = @"UPDATE goal SET player_id = @player, own_goal = @ownGoal WHERE goal_id= " + goal_id + ";";
            using (SqlCeCommand goal_update = new SqlCeCommand(goal_update_command, conn))
            {                
                goal_update.Parameters.AddWithValue("@player", newPlayerId);
                goal_update.Parameters.AddWithValue("@ownGoal", gOwnGoal);
                goal_update.ExecuteNonQuery();
            }

            //Variables used to update Match Details screen
            player_name = selectedPlayer;
            player_id = newPlayerId;
            
            //Hide this form to display the Match Details screen
            referrer.Enabled = true;
            this.Visible = false;

            //Initialise values of combo boxes and
            //checkbox for next use of form
            initClub();
            initPlayer();
            initOwnGoal();

            //Update text on Match Details screen for the Goal
            referrer.matchGoalLst.SelectedItems[0].SubItems[0].Text = player_name;
            if(goalClub.Equals("this"))
            {
                referrer.matchGoalLst.SelectedItems[0].SubItems[1].Text = club;
            }
            else
            {
                referrer.matchGoalLst.SelectedItems[0].SubItems[1].Text = otherClub;
            }

            //Disconnect from the database
            closeDatabaseConnection();
        }

        //This method is called when the 'Close' button is clicked
        private void goalCloseBtn_Click(object sender, EventArgs e)
        {
            //Hide this form to display the Match Details screen
            referrer.Enabled = true;
            this.Visible = false;

            //Cancel any changes made to the combo boxes while
            //the form was open
            initClub();
            initPlayer();
            initOwnGoal();
        }

        //This method is called when the value of the Club combo box is changed
        private void goalClubCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Find out the index of the item that was selected
            int index = goalClubCombo.SelectedIndex;
            
            //Configure global variable to indicate which club was selected
            if (index == 0)
            {
                goalClub = "this";
            }
            else
            {
                goalClub = "other";
            }

            //If the first club was selected...
            if (goalClub.Equals("this"))
            {
                //Clear the Player combo box
                goalPlayerCombo.Items.Clear();
                goalPlayerCombo.Text = "";

                //Then fill it with the players from the selected club
                for (int i = 0; i < goalThisClubPlayers.Count; i++)
                {                    
                    goalPlayerCombo.Items.Add(goalThisClubPlayers[i].name);                    
                }
            }
            //Otherwise it was the other team...
            else
            {
                //Clear the Player combo box
                goalPlayerCombo.Items.Clear();
                goalPlayerCombo.Text = "";

                //Then fill it with players from this team instead
                for (int i = 0; i < goalOtherClubPlayers.Count; i++)
                {                    
                    goalPlayerCombo.Items.Add(goalOtherClubPlayers[i].name);
                }
            }
        }

        //Method to connect to the database
        private void connectToDatabase(String connection_string)
        {
            // Retrieve the connection string
            conString = connection_string;

            // Open the connection using the connection string
            conn = new SqlCeConnection(conString);
            conn.Open();
        }

        //Method to disconnect from database
        private void closeDatabaseConnection()
        {
            //Close the database connection
            conn.Close();
        }
    }
}
